#include "stdafx.h"
#include "FxThread.h"
#ifndef LINUX_NAS
#include "process.h"
#endif
CFxThread::CFxThread(void)
{
	m_handle = NULL;
	isRunning = FALSE;
	isExited = FALSE;
	m_sleepCount = 0;
}

CFxThread::~CFxThread(void)
{
	if(isRunning || !isExited)
		Stop();
} 

void CFxThread::ThreadFunc(void* param)
{

	CFxThread* This = (CFxThread*)param;

	This->isRunning = TRUE;
	This->isExited = FALSE;

	This->Run(This);

	This->isRunning = FALSE;
	This->isExited = TRUE;
}


void CFxThread::Start()
{
	if(isRunning)
		return;  // already begin thread

	if(!Prepare())
		return;
#ifdef LINUX_NAS
	int thread_result;
	thread_result = pthread_create(&m_handle, NULL, (void*(*)(void*))ThreadFunc, (void*)this);
	if(thread_result < 0)
	{
		TRACE("Failed to create Thread in FxThread\n");
	}
	pthread_detach(m_handle);	
#else
#ifdef _DEBUG
	m_handle = (HANDLE)_beginthread(ThreadFunc, 4000000, (void*)this);
#else
	m_handle = (HANDLE)_beginthread(ThreadFunc, 0, (void*)this);
#endif
#endif

}

void CFxThread::Stop()
{

	m_sleepCount = 0;

	if(!isRunning || isExited)
	{
		isRunning = FALSE;
		isExited = TRUE;
		return;
	}

	m_sleepCount = 1;

	isRunning = FALSE;

	while(!isExited)
	{
		Sleep(10);
		m_sleepCount++;
		if (m_sleepCount > 6000)
			break;
	}

	Complete();
}
